#import "poker.h"
#import "IRCTask.h"

@implementation Messager

// shared instance is for Public
//
NSString *MessageReceivedNotification = @"MessageReceivedNotification";

+ (id)sharedInstance {
   static id shared = nil;

   if (!shared) {
       shared = [[self allocWithZone:NULL] messagerWithRecipient:@"All Players"];
   }
   return shared;
}

static NSMutableDictionary *dict = nil;

+ instanceWithRecipient:(NSString *)receipt {
    return [dict objectForKey:receipt];
}

+ (void)addInstance:(id)instance key:(NSString *)receipt {
    if (!dict) dict = [[NSMutableDictionary allocWithZone:NULL] init];
    [dict setObject:instance forKey:receipt];
}


#define END_RANGE NSMakeRange([[tv string]length],0)
+ (void)appendString:(NSString *)string toText:(NSTextView *)tv newLine:(BOOL)newLine;
{
        [tv replaceCharactersInRange:END_RANGE withString:string];
        if (newLine)
                [tv replaceCharactersInRange:END_RANGE withString:@"\n"];
        else
                [tv replaceCharactersInRange:END_RANGE withString:@" "];

        if ([[tv window] isVisible]) {
                [tv scrollRangeToVisible:END_RANGE];
        }
}

- (void)addMessage:(NSString *)message from:(NSString *)from {
    [[self class] appendString:message toText:textView newLine:YES];
}

- (void)gotMessage:(NSNotification *)notification
{
    NSString *fromWho = [notification object];
    NSDictionary *dict =  [notification userInfo];
    NSString *user = [[NSApp delegate] userName];
    if ([fromWho isEqualToString:user] || [fromWho isEqualToString:recipient]) {
	[self addMessage:[dict objectForKey:@"Message"] from:fromWho];
    }

}

+ (id)messagerWithRecipient:(NSString *)to {
    if (self = [Messager instanceWithRecipient:to]) return self;
    return [[self allocWithZone:NULL] messagerWithRecipient:to];
}

- (id)messagerWithRecipient:(NSString *)to {
   self = [self initWithWindowNibName:NSStringFromClass([self class])];
   if (self) {
       [self setWindowFrameAutosaveName:NSStringFromClass([self class])];
       [[self window] setTitle:[NSString stringWithFormat:@"Messages to %@",to]];
       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotMessage:) name:(NSString *)MessageReceivedNotification object:nil];
       [Messager addInstance:self key:to];
       recipient = [to copyWithZone:[self zone]];
   }
   return self;
}

- (IBAction)sendMessageAction:(id)sender {
   NSString *s = [sender stringValue];
   if ([recipient isEqualToString:@"All Players"])
       [[IRCTask sharedIRCTask] pushStringOverWire:[[NSString stringWithFormat:@"%@\n",s]cString]];
    else
        [[IRCTask sharedIRCTask] pushStringOverWire:[[NSString stringWithFormat:@"/msg %@ %@\n",recipient,s]cString]];

}

@end
